package com.watertek.bdcenter.bdcode.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库连接对象
 */
public class DBConnectionPool {

    private static final Logger logger = LoggerFactory.getLogger(DBConnectionPool.class);

    /**
     * hive数据源的驱动类
     */
    private static final String DRIVER_CLASS=PropertiesUtil.getValue("config/config.properties", "hive.driver.class");

    /**
     * hive源数据库的url
     */
    private static final String URL=PropertiesUtil.getValue("config/config.properties", "hive.url");

    /**
     * 源数据库的账号
     */
    private static final String USERNAME=PropertiesUtil.getValue("config/config.properties", "hive.username");

    /**
     * 源数据库的密码
     */
    private static final String PASSWORD=PropertiesUtil.getValue("config/config.properties", "hive.password");

    /**
     * druid连接池初始化大小
     */
    private static final int INIT_SIZE=Integer.parseInt(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.init_size"));

    /**
     * druid连接池最小
     */
    private static final int MIN_IDLE=Integer.parseInt(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.min_idle"));

    /**
     * druid连接池最大
     */
    private static final int MAX_ACTIVE=Integer.parseInt(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.max_active"));

    /**
     * 获取连接等待超时的时间
     */
    private static final int MAX_WAIT=Integer.parseInt(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.max_wait"));

    /**
     * 间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
     */
    private static final int TIME_BETWEEN_ECIVTION_RUNS_MILLIS=Integer.parseInt(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.time_between_eviction_runs_millis"));

    /**
     * 一个连接在池中最小生存的时间，单位是毫秒
     */
    private static final int MIN_EVICTABLE_IDLE_TIME_MILLIS=Integer.parseInt(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.min_evictable_idle_time_millis"));

    private static final String VALIDATION_QUERY=PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.validation_query");
    private static final boolean TEST_WITH_IDLE=Boolean.parseBoolean(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.test_while_idle"));
    private static final boolean TEST_ON_BORROW=Boolean.parseBoolean(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.test_on_borrow"));
    private static final boolean TEST_ON_RETURN=Boolean.parseBoolean(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.test_on_return"));

    /**
     * 打开PSCache
     */
    private static final boolean POOL_PREPARED_STATEMENTS=Boolean.parseBoolean(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.pool_prepared_statements"));

    /**
     * 指定每个连接上PSCache的大小
     */
    private static final int MAX_POOL_PREPARED_STATEMENT_PER_CONNECTION_SIZE=Integer.parseInt(PropertiesUtil.getValue("config/config.properties", "druid.connection_pool.max_pool_prepared_statement_per_connection_size"));

    private static DBConnectionPool dbConnectionPool = null;
    private static DruidDataSource druidDataSource = null;

    /**
     * 在构造函数初始化的时候获取数据库连接
     */
    private DBConnectionPool() {
        druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(DRIVER_CLASS);
        druidDataSource.setUrl(URL);
        druidDataSource.setUsername(USERNAME);
        druidDataSource.setPassword(PASSWORD);
        druidDataSource.setInitialSize(INIT_SIZE);
        druidDataSource.setMinIdle(MIN_IDLE);
        druidDataSource.setMaxActive(MAX_ACTIVE);
        druidDataSource.setMaxWait(MAX_WAIT);
        druidDataSource.setTimeBetweenEvictionRunsMillis(TIME_BETWEEN_ECIVTION_RUNS_MILLIS);
        druidDataSource.setMinEvictableIdleTimeMillis(MIN_EVICTABLE_IDLE_TIME_MILLIS);
        druidDataSource.setValidationQuery(VALIDATION_QUERY);
        druidDataSource.setTestWhileIdle(TEST_WITH_IDLE);
        druidDataSource.setTestOnBorrow(TEST_ON_BORROW);
        druidDataSource.setTestOnReturn(TEST_ON_RETURN);
        druidDataSource.setPoolPreparedStatements(POOL_PREPARED_STATEMENTS);
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(MAX_POOL_PREPARED_STATEMENT_PER_CONNECTION_SIZE);
    }

    /**
     * 数据库连接池单例
     * @return
     */
    public static synchronized DBConnectionPool getInstance(){
        if (null == dbConnectionPool){
            dbConnectionPool = new DBConnectionPool();
        }
        return dbConnectionPool;
    }

    /**
     * 返回druid数据库连接
     * @return
     * @throws SQLException
     */
    public DruidPooledConnection getConnection(){
        DruidPooledConnection druidPooledConnection=null;
        try {
            druidPooledConnection=druidDataSource.getConnection();
            return druidPooledConnection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return druidPooledConnection;
    }

    public static void main(String args[])throws Exception{
        Connection conn;
        PreparedStatement pstmt;
        ResultSet rs;
        try{
            // 获得连接:
            conn = DBConnectionPool.getInstance().getConnection();
            // 编写SQL：
            String sql = "select * from blz_anjian_txt";
            pstmt = conn.prepareStatement(sql);
            // 执行sql:
            rs = pstmt.executeQuery();
            while(rs.next()){
                System.out.println("Result: key:"+rs.getString(1) +"  –>  value:" +rs.getString(2));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}
